namespace TfsExtensions.Helper
{
    using System;
    using System.Configuration;
    using TfsExtensions.Helper.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

    /// <summary>
    /// Contains helper methods for enterprise library error logging.
    /// </summary>
    public static class ExceptionPolicyHelper
    {
        /// <summary>
        /// Exception Handling Policy
        /// </summary>
        private static string exceptionHandlePolicy;

        #region Public Methods

        /// <summary>
        /// Sets exceptionHandlePolicy from App.config
        /// </summary>
        public static void SetExceptionHandlePolicy()
        {
            try
            {
                exceptionHandlePolicy = GetExceptionHandlePolicy();
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Processes the exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public static void ProcessException(System.Exception exception)
        {
            try
            {
                ExceptionPolicy.HandleException(exception, exceptionHandlePolicy);
            }
            catch
            {
                throw;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Gets exception handling policy name from config file.
        /// </summary>
        /// <returns>Global exception policy name.</returns>
        /// <exception cref="ArgumentNullException">Global exception policy not specified in 
        /// config file.</exception>
        private static string GetExceptionHandlePolicy()
        {
            var configHost =
                ConfigurationManager.GetSection("DeploymentFrameworkConfiguration")
                as DeploymentFrameworkConfigurationSection;

            if (string.IsNullOrEmpty(configHost.ExceptionHandlingPolicy.PolicyName))
            {
                return String.Empty;
            }

            return configHost.ExceptionHandlingPolicy.PolicyName;
        }

        #endregion
    }
}